#include "stdafx.hpp"
#include "ColligereSearchDiscogsPanel.hpp"
#include "ColligereDatabaseInterfaceBase.hpp"

IMPLEMENT_DYNAMIC_CLASS ( ColligereSearchDiscogsPanel, wxPanel );

ColligereSearchDiscogsPanel::ColligereSearchDiscogsPanel()
{
	Bind ( wxEVT_COMMAND_BUTTON_CLICKED,
		&ColligereSearchDiscogsPanel::OnButtonSearch,
		XRCID ( "ID_Button_SearchDiscogs" ) );

	Bind ( wxEVT_COMMAND_LISTBOX_DOUBLECLICKED,
		&ColligereSearchDiscogsPanel::OnSearchResultDClick,
		XRCID ( "ID_ListBox_SearchResults" ) );

	Bind ( wxEVT_COMMAND_TEXT_UPDATED,
		&ColligereSearchDiscogsPanel::OnSearchTermUpdated,
		XRCID ( "ID_TextCtrl_SearchTerm" ) );
}

void ColligereSearchDiscogsPanel::OnButtonSearch ( wxCommandEvent & )
{
	XRCCTRL ( *this, "ID_Button_SearchDiscogs", wxButton )->Disable();

	XRCCTRL ( *this, "ID_ListBox_SearchResults", wxListBox )->Clear();
	mCurSearchResults.clear();

	const wxString sterm ( XRCCTRL ( *this, "ID_TextCtrl_SearchTerm", 
		wxTextCtrl )->GetValue() );

	wxASSERT ( !sterm.empty() );

	mDiscogsSearcher.SetTerm ( sterm );
	foreach ( const col::SearchDiscogs::SearchResult &r, mDiscogsSearcher.Search() )
	{
		// Note to self: Don't use wxLB_SORT in ID_ListBox_SearchResults.
		const int idx ( XRCCTRL ( *this, "ID_ListBox_SearchResults", 
			wxListBox )->Append ( r.GetTitle() ) );
		mCurSearchResults[idx] = r;
	}

	XRCCTRL ( *this, "ID_Button_SearchDiscogs", wxButton )->Enable();
}

void ColligereSearchDiscogsPanel::OnSearchResultDClick ( wxCommandEvent &rEvt )
{
	using namespace col;

	wxASSERT ( !mCurSearchResults.empty() );

	const SearchDiscogs::SearchResult r ( mCurSearchResults[rEvt.GetSelection()] );
	wxASSERT ( !r.GetUri().empty() );

	DatabaseInterfaceBase::GetActive()->GetLayout()->ClearInputControls();

	const Artist artist ( mDiscogsSearcher.DownloadResult(r) );

	DatabaseInterfaceBase::GetActive()->GetLayout()->PassItemToInputControls ( artist );
	wxASSERT ( artist.GetChildCount() != 0 );
	
	if ( artist.GetChildCount() != 0 )
	{
		DatabaseInterfaceBase::GetActive()->GetLayout()->PassItemToInputControls 
			( *artist.GetFirstChild() );
	}
}

void ColligereSearchDiscogsPanel::OnSearchTermUpdated ( wxCommandEvent & )
{
	const wxString sterm ( XRCCTRL ( *this, "ID_TextCtrl_SearchTerm", wxTextCtrl )->GetValue() );
	XRCCTRL ( *this, "ID_Button_SearchDiscogs", wxButton )->Enable ( !sterm.empty() );
}